/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package es.uah.cc.ie.ganesha;

import es.uah.cc.ie.ganesha.messaging.AlertMessage;
import es.uah.cc.ie.ganesha.messaging.position.PointPosition;
import es.uah.cc.ie.ganesha.nodes.NodeInfo;
import es.uah.cc.ie.ganesha.ontologies.PersistentOntology;
import es.uah.cc.ie.ganesha.results.GANESHAResultEntry;
import es.uah.cc.ie.ganesha.results.GANESHAResults;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.JDOMException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 *
 * @author ieru
 */
public class SAHANAListener extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            JSONParser parser = new JSONParser();

            if (request.getParameter("data") == null) {
                return;
            }

            final JSONArray incidents = (JSONArray) parser.parse(request.getParameter("data"));

            if (incidents.size() > 0) {

                new Thread() {

                    @Override
                    public void run() {
                        PersistentOntology.ONTOLOGY_WORK_WITH_FILES = true;

                        GANESHAModel model = null;
                        GANESHAConfiguration ganeshaConfig = null;

                        try {
                            ganeshaConfig = new GANESHAConfiguration(SAHANAListener.this.getServletContext().getResourceAsStream("/config.xml"));
                            model = new GANESHAModel("sahana", ganeshaConfig);
                        } catch (JDOMException ex) {
                            Logger.getLogger(SAHANAListener.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IOException ex) {
                            Logger.getLogger(SAHANAListener.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        SituationManager situationManager = new SituationManager();
                        List<AlertMessage> messages = new ArrayList<AlertMessage>();
                        //situationManager.addMessageFromXML("tso_paterna.xml");

                        for (int i = 0; i < incidents.size(); i++) {
                            JSONObject incident = (JSONObject) incidents.get(i);

                            AlertMessage msg = new AlertMessage(incident.get("name").toString());
                            msg.addPosition(new PointPosition(Double.parseDouble(incident.get("lat").toString()),
                                    Double.parseDouble(incident.get("lon").toString())));
                            msg.setEventType(incident.get("event_type").toString());

                            //System.out.println(msg.getIdentifier() + ", " + msg.getLatitude() + ", " + msg.getLongitude() + ", " + msg.getEventType());

                            messages.add(msg);
                        }

                        situationManager.addIncidents(messages);

                        model.addSituation(situationManager);

                        GANESHAResults result = model.infer();

                        System.out.println("---- POTENTIAL INCIDENTS ----");

                        if (result.getPotentialIncidents().getIncidents() != null) {
                            for (GANESHAResultEntry<AlertMessage> i : result.getPotentialIncidents().getIncidents()) {
                                System.out.println("\t- Regular incident with identifier " + i.message.getIdentifier());
                                for (NodeInfo n : i.nodes) {
                                    System.out.println("\t\t* Node: " + n.toString());
                                }
                            }
                        }

                        //SAHANAReport.sendResultsToSAHANA(ganeshaConfig, result);
                    }
                }.start();
            }

            //out.println("holaaaa");
            // TODO output your page here
            //out.println("{ data : \"Processing incidents... check your map later.\" }");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
